// test user-level fault handler -- alloc pages to fix faults

#include <inc/lib.h>

void
handler(struct UTrapframe *utf)
{
	int r;
	void *addr = (void*)utf->utf_fault_va;
        static int count = 0;

	cprintf("fault %x\n", addr);
        count++;
        cprintf(">>> %s count=%d\n", __FUNCTION__, count);
	if ((r = sys_page_alloc(0, ROUNDDOWN(addr, PGSIZE),
				PTE_P|PTE_U|PTE_W)) < 0)
		panic("allocating at %x in page fault handler: %e", addr, r);
        cprintf(">>> %s count=%d\n", __FUNCTION__, count);
	snprintf((char*) addr, 100, "this string was faulted in at %x", addr);
        cprintf(">>> %s count=%d\n", __FUNCTION__, count);
}

void
umain(void)
{
	set_pgfault_handler(handler);

        /*
         * 0xDeadBeef will not cause nest page fault
         * 0xCafeBffe will cause nest page fault, 0xCafeBffe + 100 exceed the page boundary
         */
	cprintf("%s\n", (char*)0xDeadBeef);
	cprintf("%s\n", (char*)0xCafeBffe);
}
